#include "recbox.h"
#include "ui_recbox.h"

RecBox::RecBox(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RecBox),
    row(1),
    col(4)
{
    ui->setupUi(this);
//    RecBoxItem* item = new RecBoxItem(this);
//    ui->recListUplHLayout->addWidget(item);
}

RecBox::~RecBox()
{
    delete ui;
}

void RecBox::initRecBoxUi(QJsonArray data, int row)
{
    if(row == 2)
    {
        //证明是2行4列
        this->row = row;
        this->col = 8;
    }
    else
    {
        //需要隐藏一行
        ui->recListDown->hide();
    }
    //存储数据
    imageList = data;
    //开始添加数据
    curIndex = 0;
    count = imageList.size()/col;
    createRecItem();
}

void RecBox::createRecItem()
{
    //考虑到翻页的缘故，我们需要先清除所有的item，才能再次把新的内容填入
    QList<RecBoxItem*>recUpList = ui->recListUp->findChildren<RecBoxItem*>();
    for(auto*e:recUpList)
    {
        ui->recListUpHLayout->removeWidget(e);
        delete e;
    }
    QList<RecBoxItem*>recDownList = ui->recListDown->findChildren<RecBoxItem*>();
    for(auto*e:recDownList)
    {
        ui->recListDownHLayout->removeWidget(e);
        delete e;
    }
    //qDebug()<<"row"<<endl;
    int index = 0;
    for(int i = curIndex*col;i<col+curIndex*col;++i,index++)
    {
        RecBoxItem* item = new RecBoxItem(this);
        QJsonObject obj = imageList[i].toObject();
        item->setImage(obj.value("path").toString());
        item->setText(obj.value("text").toString());
        //将RecBoxItem对象添加到RecBox对象中
        if(index>=4&&2==row)
        {
            ui->recListDownHLayout->addWidget(item);
        }
        else
        {
            ui->recListUpHLayout->addWidget(item);
        }
    }
}

void RecBox::on_btUp_clicked()
{
    //向前翻页，如果当前页为第一页，让curIndex指向最后一页
    if(curIndex == 0)
    {
        curIndex = count-1;
    }
    else
    {
        curIndex--;
    }
    createRecItem();
}

void RecBox::on_btDown_clicked()
{
    //向后翻页，如果当前页为最后一页那么回到第一页
    if(curIndex == count-1)
        curIndex = 0;
    else
        curIndex++;
    createRecItem();
}
